package com.jxbeidou.system.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import com.jxbeidou.core.entity.PageResult;
import com.jxbeidou.core.mybatis.service.impl.BaseServiceImpl;
import com.jxbeidou.core.mybatis.convert.PageResultConvert;
import com.jxbeidou.system.user.convert.UserRoleConvert;
import com.jxbeidou.system.user.entity.UserRoleDO;
import com.jxbeidou.system.user.query.UserRoleQuery;
import com.jxbeidou.system.user.vo.UserRoleVO;
import com.jxbeidou.system.user.mapper.UserRoleMapper;
import com.jxbeidou.system.user.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import jakarta.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关系表
 *
 * @author 杜晓祥 
 * @since 1.0.0 2023-12-14
 */
@Service
@Slf4j
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper, UserRoleDO> implements UserRoleService {

    @Override
    public PageResult<UserRoleVO> page(UserRoleQuery query) {
        IPage<UserRoleDO> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        PageResult<UserRoleVO> result = PageResultConvert.convert(page, entityList -> UserRoleConvert.INSTANCE.convertList(entityList));
        return result;
    }

    @Override
    public List<String> findByUserId (Long userId) {
        log.debug("findByUserId:[{}]");
        if (userId == null) {
            return Collections.EMPTY_LIST;
        }
        LambdaQueryWrapper<UserRoleDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(userId != null, UserRoleDO::getUserId, userId);
        List<UserRoleDO> list = baseMapper.selectList(wrapper);
        if (ObjectUtils.isEmpty(list)) {
            return Collections.EMPTY_LIST;
        }
        return list.stream().map(e -> Long.toString(e.getRoleId())).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<UserRoleDO> getWrapper(UserRoleQuery query){
        LambdaQueryWrapper<UserRoleDO> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    public void save(UserRoleVO vo) {
        UserRoleDO entity = UserRoleConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
    }

    @Override
    public void update(UserRoleVO vo) {
        UserRoleDO entity = UserRoleConvert.INSTANCE.convert(vo);
        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}